import axios from 'axios'
import { message } from 'ant-design-vue'
import {useCounterStore} from '@/stores/index.js'
import Router from "@/router/index";
import JSONBig  from 'json-bigint'
const service = axios.create({
  baseURL: '/api',
  timeout: 500000 // 超时
})
service.defaults.transformResponse = [(data) => {
  var json = JSONBig({
    storeAsString:true
  })
  return json.parse(data)
}]

service.interceptors.request.use(
  config => {
// 注意
const store = useCounterStore()
     // 设置请求token
     config.cancelToken = new axios.CancelToken (c => {
      store.setCancelToken (c);
    });
    if (store.token?.value) {
      // 设置请求token
      config.headers[store.token.name] = store.token.value
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    console.log(1111)
    console.log(response)
    const res = response.data
    if (res.status === 'error') {
        message.error(res.msg || 'Error')
      return Promise.reject(res.message)
    } else {
      // 正常情况
      return res
    }
  },
  error => {
    const store = useCounterStore()
    const code = error.response?.status
    console.log(error.response)
    console.log(Router)
    switch (code) {
      case 400:
        error.message = error.response.data.message || '请求错误'
        break
      case 401:
        error.message = error.response.data.message || '未授权,请重新登陆'
        // store.resetState()
           Router.push({
            path: '/login',
            query:{
              type:'unlogin'
            }
          })
        break
      case 403:
        error.message = error.response.data.msg || '拒绝访问'
        break
      case 404:
        error.message = error.response.data.msg || `请求地址出错: ${error.response.config.url}`
        break
      case 408:
        error.message = error.response.data.msg || '请求超时'
        break
      case 500:
        error.message = error.response.data.msg || error.response.data.message || '服务器内部错误'
        break
      case 501:
        error.message = error.response.data.msg || '服务未实现'
        break
      case 502:
        error.message = error.response.data.msg || '网关错误'
        break
      case 503:
        error.message = error.response.data.msg || '服务不可用'
        break
      case 504:
        error.message = error.response.data.msg || '网关超时'
        break
      case 505:
        error.message = error.response.data.msg || 'HTTP版本不受支持'
        break
      default:
        error.message = error.response.data.msg || '系统异常'
        break
    }
     
    if(code != 401){
      message.error(error.message)
    }

 
    return Promise.reject(error)
  }
)

export default service
